﻿//-----------------------------------------------------------------------
// <Copyright>
// * Copyright (C) 2022 RuYiAdmin All Rights Reserved
// </Copyright>
//-----------------------------------------------------------------------

using MongoDB.Driver;
using RuYiAdmin.Net.Common.Global;
using System;

namespace RuYiAdmin.Net.Common.Utility
{
    /// <summary>
    /// MongoDB工具类
    /// </summary>
    public static class RuYiMongoDBContext
    {
        /// <summary>
        /// Lazy对象
        /// </summary>
        private static readonly Lazy<MongoClient> LazyInstance = new Lazy<MongoClient>(() =>
        {
            var client = new MongoClient(RuYiAdminGlobalContext.MongoDBConfig.MongoUrl);
            return client;
        });

        /// <summary>
        /// 单例对象
        /// </summary>
        public static MongoClient Instance { get { return LazyInstance.Value; } }

        /// <summary>
        /// 是否已创建
        /// </summary>
        public static bool IsInstanceCreated { get { return LazyInstance.IsValueCreated; } }

        /// <summary>
        /// 获取业务集合
        /// </summary>
        /// <typeparam name="TDocument">TDocument</typeparam>
        /// <param name="mongoClient">mongoClient</param>
        /// <param name="collectionName">collectionName</param>
        /// <returns>IMongoCollection</returns>
        public static IMongoCollection<TDocument> GetBusinessCollection<TDocument>(this MongoClient mongoClient, String collectionName)
        {
            IMongoDatabase db = mongoClient.GetDatabase(RuYiAdminGlobalContext.MongoDBConfig.MongoDefaultDB);
            IMongoCollection<TDocument> mongoCollection = db.GetCollection<TDocument>(collectionName);
            return mongoCollection;
        }
    }
}
